package com.lanou.sfu.songforu.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.base.BaseAcitvity;
import com.lanou.sfu.songforu.datas.MusicListDatas;
import com.lanou.sfu.songforu.datas.RecommendPlayDatas;
import com.lanou.sfu.songforu.entity.ArtistListEntity;
import com.lanou.sfu.songforu.fragment.AboutFragment;
import com.lanou.sfu.songforu.fragment.CollectListFragment;
import com.lanou.sfu.songforu.fragment.MainPagerFragment;
import com.lanou.sfu.songforu.fragment.RecommendViewFragment;
import com.lanou.sfu.songforu.fragment.SettingFragment;
import com.lanou.sfu.songforu.music_library_fragment.ArtistDetailFragment;
import com.lanou.sfu.songforu.network.NetState;
import com.lanou.sfu.songforu.network.TipsToast;
import com.lanou.sfu.songforu.service.PlayerService;
import com.lanou.sfu.songforu.slidingmenu.LeftFragment;
import com.lanou.sfu.songforu.slidingmenu.SlidingMenu;
import com.lanou.sfu.songforu.view.MusicInterface;
import com.lanou.sfu.songforu.view.MusicPopuoWindow;
import com.lanou.sfu.songforu.view.Time;

import java.util.ArrayList;
import java.util.List;

import it.sephiroth.android.library.picasso.Picasso;

public class MainActivity extends BaseAcitvity implements View.OnClickListener{
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private MainPagerFragment fragment;
    public boolean isDestroy = false;
    private static ImageView startBtn;
    private static ImageView nextBtn, songLists,singerImage;
    private static TextView musicName, musicAuthers;
    private static MusicInterface music;
    private MusicPopuoWindow musicPopuoWindow;
    private static TextView timeStart, timeEnd;
    private ArrayList<MusicListDatas> listDatases;
    private static Context mContext;

    private static TipsToast tipsToast;
    TextView text_type;


    //构建一个服务连接对象
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //服务连接成功
            music = (MusicInterface) service;

        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("服务连接错误");
        }
    };
    private SlidingMenu mSlidingMenu;
    private LeftFragment leftFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 注册广播接收器Start
        NetState receiver = new NetState();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);
        receiver.onReceive(this, null);

        setContentView(R.layout.sliding_main);
            mContext = this;
//        EventBus.getDefault().register(this);
        mSlidingMenu = (SlidingMenu) findViewById(R.id.slidingMenu);
        mSlidingMenu.setLeftView(getLayoutInflater().inflate(R.layout.left_menu, null));
        mSlidingMenu.setCenterView(getLayoutInflater().inflate(R.layout.activity_main, null));
        //替换侧滑菜单
        leftFragment = new LeftFragment();
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.replace(R.id.left_frame, leftFragment);
        //替换主Fragment
        fragment = new MainPagerFragment();
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_main, fragment);
        transaction.commit();
        //播放歌曲
        startBtn = (ImageView) findViewById(R.id.playBtn);
        nextBtn = (ImageView) findViewById(R.id.nextBtn);
        songLists = (ImageView) findViewById(R.id.songLists);
        songLists.setOnClickListener(this);
        startBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        //歌曲名和作者名
        musicName = (TextView) findViewById(R.id.music_play_name);
        musicAuthers = (TextView) findViewById(R.id.music_play_authers);
        singerImage = (ImageView) findViewById(R.id.singerImage);
        singerImage.setOnClickListener(this);
        //时间
        timeStart = (TextView) findViewById(R.id.timeStart);
        timeEnd = (TextView) findViewById(R.id.timeEnd);
        //绑定服务
        Intent intent = new Intent(this, PlayerService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        init();
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {// 根据反馈值判断当前网络状态
            case 1:
                String keyStr = data.getStringExtra("key");
                System.out.println("--------- onActivityResult -------keyStr="
                        + keyStr);
                if ("-1".equals(keyStr)) {
                    showTips(R.mipmap.tips_error, "网络不可用...");
                } else {
                    showTips(R.mipmap.tips_smile, "网络已恢复正常...");

                }

                break;
        }
    }


    /**
     * 自定义taost
     *
     * @param iconResId
     *            图片
     * @param -msgResId
     *            提示文字
     */
    public void showTips(int iconResId, String tips) {
        if (tipsToast != null) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                tipsToast.cancel();
            }
        } else {
            tipsToast = TipsToast.makeText(getApplication().getBaseContext(),
                    tips, TipsToast.LENGTH_SHORT);
        }
        tipsToast.show();
        tipsToast.setIcon(iconResId);
        tipsToast.setText(tips);
    }



//    public void onEvent(MyEvent.GetData event) {
//        if (event.isGet()) {
//            startBtn.setChecked(true);
//        }
//    }

    //侧滑
    private void init() {
        fragment.setMyPageChangeListener(new MainPagerFragment.MyPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                if (fragment.isFirst()) {
                    mSlidingMenu.setCanSliding(true, false);
                } else {
                    mSlidingMenu.setCanSliding(false, false);
                }
            }
        });
    }

    public void showLeft() {
        mSlidingMenu.showLeftView();
    }


    //跳转到framgent
    public void toFramgent(Fragment mFragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_main, mFragment)
                .commit();
    }

    // 返回键退出
    private long exitTime = 0;

    // 监听手机上的BACK键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

                // 判断两次点击的时间间隔（默认设置为2秒）
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //轮播图片跳转
    public void skepFragemnt(int position, List<RecommendPlayDatas.PicEntity> datases) {
        RecommendViewFragment fragment = new RecommendViewFragment();
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_main, fragment)
                .commit();
        String ID = datases.get(position % datases.size()).getCode();
        String title = datases.get(position % datases.size()).getRandpic_desc();
        Bundle bundle = new Bundle();
        bundle.putString("ID", ID);
        bundle.putString("title", title);
        fragment.setArguments(bundle);
    }

    public void transData(List<ArtistListEntity.ArtistEntity> lists, int position) {
        Bundle bundle = new Bundle();
        String artistId = lists.get(position).getTing_uid();
        String artistPic = lists.get(position).getAvatar_big();
        bundle.putString("picUrl", artistPic);
        bundle.putString("artistID", artistId);
        ArtistDetailFragment fragment = new ArtistDetailFragment();
        fragment.setArguments(bundle);
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_main, fragment)
                .commit();
    }

    @Override
    public void onDestroy() {
        isDestroy = true;
        //解绑服务
        unbindService(connection);
        super.onDestroy();
    }

    //播放控制
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playBtn://播放
                Log.i("TAG", music.getIsPlay()+"\n" + music.getDuration() +"\n" + music.getProgress());
                if (music.getIsPlay()) {
                    music.pause();
                }else if (!music.getIsPlay() && music.getDuration() > music.getProgress()){
                    music.continuePlay();
                }
                break;
            case R.id.nextBtn://下一首
                music.next();
                break;
            case R.id.songLists://播放队列
                listDatases = music.musicList();
                musicPopuoWindow = new MusicPopuoWindow(music,this, listDatases);
                //显示窗口
                musicPopuoWindow.showAtLocation(MainActivity.this.findViewById(R.id.player),
                        Gravity.RIGHT, 0, 102); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.singerImage:
                Intent intent = new Intent(this,PlayerQueueActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.pushup_in,R.anim.pushout_out);
        }
    }
    //播放列表监听
    public View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.songLists:
                    musicPopuoWindow.dismiss();
                    break;
            }

        }
    };
    //静态方法 用来传值
    public static void play(ArrayList<MusicListDatas> lists, int position) {
        Log.i("cxh", "当前点击了第" + position);
        music.play(lists, position);
    }

    public static void clean() {
        music.clean();
    }
    //不断获得当前进度的方法
    public static Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");//最大时长
            int currentPosition = bundle.getInt("currentPosition");//当前播放时长
            //转换时间格式
            timeStart.setText(Time.formatTime((long) currentPosition));
            timeEnd.setText(Time.formatTime((long) duration));
            //改变按钮状态
            if (music.getIsPlay()) {
                startBtn.setImageResource(R.mipmap.night_biz_audio_btn_pause);
            } else {
                startBtn.setImageResource(R.mipmap.night_biz_audio_btn_play);
            }
            //设置歌曲名 作者名
            musicName.setText(music.getName());
            musicAuthers.setText(music.getSinger());
            if (music.getImage() != null) {
                Picasso.with(mContext).load(music.getImage()).placeholder(R.mipmap.music).into(singerImage);
            }else {
                singerImage.setImageResource(R.mipmap.music);
            }
            return false;
        }
    });

    public void setting(View v) {
        mSlidingMenu.showLeftView();
        SettingFragment fragment = new SettingFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_main,fragment).addToBackStack(null).commit();
    }

    public void collect(View v){
        mSlidingMenu.showLeftView();
        CollectListFragment fragment = new CollectListFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_main,fragment).addToBackStack(null).commit();

    }


    public void about(View v){
        mSlidingMenu.showLeftView();
        AboutFragment fragment = new AboutFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_main,fragment).addToBackStack(null).commit();
    }

}
